package com.cherry.androidviewdemo.widget

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.cherry.androidviewdemo.R

/**
 * @author DongMS
 * @since 2020/6/5
 */
class RatingBarView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defStyle: Int = 0) : View(context, attributeSet, defStyle) {

    var normalBitmap: Bitmap
    var focusBitmap: Bitmap

    var starNum = 5

    private var currentFocusStar = 0

    init {
        val array = context.obtainStyledAttributes(attributeSet, R.styleable.RatingBarView)
        val normalStarDrawable = array.getResourceId(R.styleable.RatingBarView_normalStarRes, R.mipmap.ratingbar_normal)
        val focusStarDrawable = array.getResourceId(R.styleable.RatingBarView_focusStarRes, R.mipmap.ratingbar_focus)
        starNum = array.getInt(R.styleable.RatingBarView_starNum, starNum)
        array.recycle()

        normalBitmap = BitmapFactory.decodeResource(resources, normalStarDrawable)
        focusBitmap = BitmapFactory.decodeResource(resources, focusStarDrawable)

    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //两张图片宽高必须是一样的，所以这里只是取其中一张进行测量
        val width = normalBitmap.width * starNum + paddingLeft + paddingRight
        val height = normalBitmap.height + paddingTop + paddingBottom
        setMeasuredDimension(width, height)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val width = normalBitmap.width
        for (i in 0 until starNum) {
            if (currentFocusStar > i) {
                canvas.drawBitmap(focusBitmap, (i * width + paddingLeft).toFloat(), paddingTop.toFloat(), null)
            } else {
                canvas.drawBitmap(normalBitmap, (i * width + paddingLeft).toFloat(), paddingTop.toFloat(), null)
            }
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_MOVE) {
            val dx = event.x - paddingLeft
            var touchStar = (dx / normalBitmap.width).toInt() + 1

            //边界判断
            if (touchStar < 0) {
                touchStar = 0
            }
            if (touchStar > starNum) {
                touchStar = starNum
            }

            if (touchStar == currentFocusStar) {
                return true
            }
            currentFocusStar = touchStar
            invalidate()
        }
        return true
    }


}